var LocalStrategy = require('passport-local').Strategy;
var User = require('../models/User');
var constant = require('./constant');
var JwtStrategy = require('passport-jwt').Strategy;

module.exports = function(passport){
	passport.use('local-signUp', new LocalStrategy({
		usernameField: 'email',
		passwordField: 'password',
		passReqToCallback: true
	},function(req, username, password, done){
		if(!req.body.name){
			done(null,false,{desc:constant.nameRequired});
		}
		if(!req.body.username){
			done(null,false,{desc:constant.usernameRequired});
		}
		if(!req.body.email){
			done(null,false,{desc:constant.emailRequired});
		}
		if(!req.body.password){
			done(null,false,{desc:constant.passwordRequired});
		}
		if(req.body.password!=req.body.confirmPwd){
			done(null,false,{desc:constant.passwordNonConsistent});
		}
		User.findOne({email:username}, function(err, user){
			if(err)
				return done(err);
			if(user)
				return done(null, false,{desc:constant.emailAlreadyExit});
			else{
				User.findOne({username:req.body.username}, function(err, user){
					if(err)
						return done(err);
					if(user)
						return done(null, false,{desc:constant.usernameAlreadyExit});
					else{
						var newUser = new User();
						newUser.name = req.body.name;
						newUser.username = req.body.username;
						newUser.email = req.body.email;
						newUser.password = newUser.genHash(req.body.password);
						// newUser.save(function(err, user){
						// 	if(err){
						// 		throw err;
						// 	}
						// 	done(null, user);
						// });
						done(null, newUser);
					}
				});
			}
		})
	}));

	passport.use('local-signIn', new LocalStrategy({
		usernameField: 'email',
		passwordField: 'password',
		passReqToCallback: true
	},function(req, username, password, done){
		if(!req.body.email){
			done(null,false,{desc:constant.emailRequired});
		}
		if(!req.body.password){
			done(null,false,{desc:constant.passwordRequired});
		}
		User.findOne({email:username}, function(err, user){
			if(err)
				return done(err);
			if(!user)
				return done(null, false,{desc:constant.emailNotRegister});
			else if(!user.verifyPassword(password)){
				return done(null, false,{desc:constant.invalidPassword});
			}else{
				return done(null, user,{desc:constant.signInSucc});
			}
		})
	}));

	passport.use(new JwtStrategy(constant.secret, {}, function(jwt_paylaod, done) {
    	User.findOne({_id:jwt_paylaod.id}, function(err, user){
    		if(err)
    			return done(err);
    		if(!user){
    			return done(null, false, {desc: constant.userNotFound});
    		}else{
    			return done(null, user);
    		}
    	});
	}));

	passport.use('jwt-reset-pwd', new JwtStrategy(constant.resetPwdSecret, {}, function(jwt_paylaod, done) {
    	User.findOne({_id:jwt_paylaod.id}, function(err, user){
    		if(err)
    			return done(err);
    		if(!user){
    			return done(null, false, {desc: constant.userNotFound});
    		}else{
    			return done(null, user);
    		}
    	});
	}));
}

